package router

import (
	"apibe/single/src/v1/router/handler"
	"apibe/single/src/v1/service/impl"
	"apibe/single/src/v1/share/crypt"
	"apibe/single/src/v1/share/middler"
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
)

func Design(c *gin.Context) {
	var catch map[string]string
	apiName := c.Param("api_name")
	claims := c.MustGet(middler.CLAIMS).(*crypt.CustomClaims)
	err := c.ShouldBindJSON(&catch)
	if err != nil {
		c.JSON(http.StatusBadRequest, err.Error())
		return
	}
	bytes, status, cache, err := handler.DesignHandler(catch, apiName, claims)
	c.Writer.Header().Set("Cache", strconv.FormatBool(cache))
	if err != nil {
		c.JSON(status, err.Error())
		return
	}
	_, _ = c.Writer.Write(bytes)
}

func DesignUpsert(c *gin.Context) {
	var d impl.Design
	claims := c.MustGet(middler.CLAIMS).(*crypt.CustomClaims)
	err := c.ShouldBindJSON(&d)
	if err != nil {
		c.Set(middler.CODE, middler.ErrReq)
		c.Set(middler.MSG, err.Error())
		return
	}
	err = handler.DesignUpsertHandler(&d, claims)
	if err != nil {
		c.Set(middler.CODE, middler.ErrMgo)
		c.Set(middler.MSG, err.Error())
		return
	}
	c.Set(middler.RESULT, "SUCCESS")
}

func DesignFindMany(c *gin.Context) {
	var in struct {
		Filter   map[string]interface{} `json:"filter"`
		Page     int                    `json:"page"`
		PageSize int                    `json:"page_size"`
	}
	err := c.ShouldBindJSON(&in)
	if err != nil {
		c.Set(middler.CODE, middler.ErrReq)
		c.Set(middler.MSG, err.Error())
		return
	}
	designList, count, err := handler.DesignFindManyHandler(in.Filter, in.Page, in.PageSize)
	if err != nil {
		c.Set(middler.CODE, middler.ErrMgo)
		c.Set(middler.MSG, err.Error())
		return
	}
	result := map[string]interface{}{
		"total": count,
		"data":  *designList,
	}
	c.Set(middler.RESULT, result)
}
